package com.zdemo.pressure.simple;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;

import com.zdemo.common.Logging;

public class Request {

	public static final ExecutorService exec = Executors.newFixedThreadPool(
			100, new RequestThreadFactory("RequestPool"));
	private static final Logger log = Logging.getLogger();
	private static final ThreadLocal<Long> startTimes = new ThreadLocal<Long>();
	private static final AtomicLong totalTime = new AtomicLong();

	public static void main(String[] args) {
		for (int i = 0; i < 1; i++) {
			exec.execute(new Runnable() {
				@Override
				public void run() {
					for(int i = 0; i < 100; i++) {
						String result = getResult("http://222.35.5.13:20081");
						System.out.println(result);
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
		}
		exec.shutdown();
		while (true) {
			if (exec.isTerminated()) {
//				log.info("总耗时:" + totalTime.longValue() / 1000 + " s");
				break;
			}

		}
	}

	private static String getResult(String target) {
		long start = System.currentTimeMillis();
		startTimes.set(start);
		URL url;
		URLConnection urlconn;
		String result = "";
		int status = 0;
		try {
			url = new URL(target);
			urlconn = url.openConnection();
			urlconn.setConnectTimeout(3000);
			urlconn.setReadTimeout(3000);
			HttpURLConnection httpConnection = (HttpURLConnection) urlconn;
			status = httpConnection.getResponseCode();
		} catch (IOException e) {
			// e.printStackTrace();
		} finally {
			long taskTime = System.currentTimeMillis()
					- startTimes.get();
			totalTime.addAndGet(taskTime);
			System.out.println("耗时：" + taskTime + " ms, 结果：" + status);
		}
		return target;
	}
	
//	public static String inputStream2String(InputStream in) throws IOException {
//		StringBuffer out = new StringBuffer();
//		byte[] b = new byte[4096];
//		for (int n; (n = in.read(b)) != -1;) {
//			out.append(new String(b, 0, n));
//		}
//		return out.toString();
//	}
}
